//
//  KABMineVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/1/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMineVC.h"
#import "KABSettingVC.h"
#import "KABMineEntryMsgVC.h"
#import <UINavigationBar+Awesome.h>
#import "UIColor+XDHex.h"
#import "KABMineTCell.h"
#import "KABHomepageVC.h"
#import "KABMineUserListVC.h"
#import "KABMineTicketVC.h"
#import "KABMineFollowExhVC.h"
#import "KABMineColProVC.h"
#import "KABMineColShopVC.h"
#import "KABMineColCosVC.h"
#import "KABMallMyOrderVC.h"
#import "KABExhOrderVC.h"
#import "KABMallReturnProVC.h"
#import <YYWebImage.h>
#import "KABModel.h"
#import "GlobalHeader.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABMallMyShopVC.h"
#import "KSPhotoBrowser.h"
#import "ThemeManager.h"

@interface KABMineVC ()<UITableViewDelegate, UITableViewDataSource, KABMineTCellDelegate>
@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak, nonatomic) IBOutlet UIImageView *portraitImgView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *autographLabel;
@property (weak, nonatomic) IBOutlet UIButton *followBtn;
@property (weak, nonatomic) IBOutlet UIButton *fansBtn;
@property (weak, nonatomic) IBOutlet UIButton *cosBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIView *msgRedDot;

@property (strong, nonatomic) NSArray<NSArray *> *titleArray;

//@property (nonatomic, readonly) KABMineInfo *mineInfo;
@property (nonatomic, readonly) KABLoginModel *userInfo;

@end

static NSString *const kReuseCellId = @"KABMineTCell";

@implementation KABMineVC

#pragma mark - life cycle
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ThemeManagerThemeDidChangedNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(themeDidChangeHandle:) name:ThemeManagerThemeDidChangedNotification object:nil];
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"我";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mine_message"] style:UIBarButtonItemStylePlain target:self action:@selector(msgBarBtnTapped:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mine_setting"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarBtnTapped:)];
    [self.navigationController.navigationBar addSubview:self.msgRedDot];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)initSubViews {
    self.portraitImgView.layer.masksToBounds = YES;
    self.portraitImgView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.portraitImgView.layer.cornerRadius = CGRectGetWidth(self.portraitImgView.bounds) / 2.0;
    self.portraitImgView.layer.borderWidth = 2;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(portraitImgViewTapped:)];
    [self.portraitImgView addGestureRecognizer:tapGesture];
    
    self.followBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.followBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.followBtn setTitle:@"18\n关注" forState:UIControlStateNormal];
    [self.followBtn addTarget:self action:@selector(followBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.fansBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.fansBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.fansBtn setTitle:@"18\n粉丝" forState:UIControlStateNormal];
    [self.fansBtn addTarget:self action:@selector(fansBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.cosBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.cosBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.cosBtn setTitle:@"18\nCos" forState:UIControlStateNormal];
    [self.cosBtn addTarget:self action:@selector(cosBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.tableHeaderView = self.headerBgView;
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 111.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 未读消息红点的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(msgRedDotHandle:) name:KABGlobalNotiMsgRedDotShow object:nil];
    // 导航栏颜色
    UIColor *navBgColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMineBgColor];
    [self.navigationController.navigationBar lt_setBackgroundColor:navBgColor];
    
    [self requestMineInfo];
    [self requestCosLikeAndCommentCnt];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 红点的通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KABGlobalNotiMsgRedDotShow object:nil];
    // 导航栏颜色
    [self.navigationController.navigationBar lt_reset];
    
    self.msgRedDot.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.titleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArray[section].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMineTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    NSDictionary *dic = self.titleArray[indexPath.section][indexPath.row];
    cell.titleLabel.text = dic[@"title"];
    cell.showDetails = [dic[@"isExpanded"] boolValue];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.titleArray[indexPath.section][indexPath.row];
    if ([dic[@"title"] isEqualToString:@"个人主页"]) {
        KABHomepageVC *vc = [[KABHomepageVC alloc] init];
        vc.user_id = [KABModel sharedInstance].userInfo.uid;
        vc.user_name = [KABModel sharedInstance].userInfo.nick_name;
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([dic[@"title"] isEqualToString:@"我的店铺"]) {
        [self jumpToMyShop];
    } else if ([dic[@"title"] isEqualToString:@"我的门票"]) {
        KABMineTicketVC *vc = [[KABMineTicketVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([dic[@"title"] isEqualToString:@"关注的展会"]) {
        KABMineFollowExhVC *vc = [[KABMineFollowExhVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([dic[@"title"] isEqualToString:@"展会订单"]) {
        KABExhOrderVC *vc = [[KABExhOrderVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - KABMineTCellDelegate
- (void)kABMineTCell:(KABMineTCell *)cell colProBtnTapped:(UIButton *)btn {
    KABMineColProVC *vc = [[KABMineColProVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)kABMineTCell:(KABMineTCell *)cell colShopBtnTapped:(UIButton *)btn {
    KABMineColShopVC *vc = [[KABMineColShopVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)kABMineTCell:(KABMineTCell *)cell orderBtnTapped:(UIButton *)btn {
    KABMallMyOrderVC *vc = [[KABMallMyOrderVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
//    KABMallReturnProVC *vc = [[KABMallReturnProVC alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - event response
- (void)themeDidChangeHandle:(NSNotification *)notification {
    [self refreshWholeView];
}

- (void)msgRedDotHandle:(NSNotification *)notification {
    NSInteger newMsgCnt = [RCIMClient sharedRCIMClient].getTotalUnreadCount;
    newMsgCnt += [KABModel sharedInstance].mineNewMsg.totalNewMsgCnt;
    self.msgRedDot.hidden = (newMsgCnt > 0) ? NO : YES;
}

- (void)msgBarBtnTapped:(UIBarButtonItem *)barBtn {
    KABMineEntryMsgVC *vc = [[KABMineEntryMsgVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)settingBarBtnTapped:(UIBarButtonItem *)barBtn {
    KABSettingVC *vc = [[KABSettingVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)portraitImgViewTapped:(UIGestureRecognizer *)gesture {
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:(UIImageView *)gesture.view
                                                    imageUrl:[NSURL URLWithString:self.userInfo.headimg_url]];
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:@[photoItem] selectedIndex:0];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}
- (void)followBtnTapped:(UIButton *)btn {
    KABMineUserListVC *vc = [[KABMineUserListVC alloc] initWithViewType:KABMineUserListVCTypeFollow];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)fansBtnTapped:(UIButton *)btn {
    KABMineUserListVC *vc = [[KABMineUserListVC alloc] initWithViewType:KABMineUserListVCTypeFans];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)cosBtnTapped:(UIButton *)btn {
    KABMineColCosVC *vc = [[KABMineColCosVC alloc] init];
    vc.viewType = KABMineColCosVCTypeCollected;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - private methods
- (void)jumpToMyShop {
    if (!self.userInfo.misc_detail.is_merchant) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"您还未开通个人店铺" message:@"个人店铺需要到咔咘官网(https://tokabu.com)申请开通" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    
    KABMallMyShopVC *vc = [[KABMallMyShopVC alloc] init];
    vc.shop_owner_id = [KABModel sharedInstance].userInfo.uid;
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.headerBgView.backgroundColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerMineBgColor];
    
    [self.portraitImgView yy_setImageWithURL:[NSURL URLWithString:self.userInfo.headimg_url] placeholder:[KABDefaultVarModel sharedInstance].smallDefaultImg];
    self.nameLabel.text = self.userInfo.nick_name;
    self.nameLabel.textColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerNavTintColor];
    self.autographLabel.text = self.userInfo.sign;
    self.autographLabel.textColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerNavTintColor];
    
    UIColor *titleColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerNavTintColor];
    NSDictionary *dic = @{NSForegroundColorAttributeName : (titleColor ? titleColor : [UIColor whiteColor]),
                          NSFontAttributeName : [UIFont systemFontOfSize:10.0]};
    
    {
        NSString *totalFollowStr = [NSString stringWithFormat:@"%zd", self.userInfo.misc_detail.total_follow];
        NSString *followStr = [NSString stringWithFormat:@"%@\n我的关注", totalFollowStr];
        NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:followStr];
        [mAStr addAttributes:dic range:NSMakeRange(totalFollowStr.length, followStr.length - totalFollowStr.length)];
        [self.followBtn setAttributedTitle:mAStr forState:UIControlStateNormal];
    }
    
    {
        NSString *totalFansStr = [NSString stringWithFormat:@"%zd", self.userInfo.misc_detail.total_fans];
        NSString *fansStr = [NSString stringWithFormat:@"%@\n我的粉丝", totalFansStr];
        NSMutableAttributedString *mFansAStr = [[NSMutableAttributedString alloc] initWithString:fansStr];
        [mFansAStr addAttributes:dic range:NSMakeRange(totalFansStr.length, fansStr.length - totalFansStr.length)];
        [self.fansBtn setAttributedTitle:mFansAStr forState:UIControlStateNormal];
    }
    
    {
        NSString *totalCosStr = [NSString stringWithFormat:@"%zd", self.userInfo.misc_detail.total_collect_cosplay];
        NSString *cosStr = [NSString stringWithFormat:@"%@\n收藏的Cos", totalCosStr];
        NSMutableAttributedString *mCosAStr = [[NSMutableAttributedString alloc] initWithString:cosStr];
        [mCosAStr addAttributes:dic range:NSMakeRange(totalCosStr.length, cosStr.length - totalCosStr.length)];
        [self.cosBtn setAttributedTitle:mCosAStr forState:UIControlStateNormal];
    }
}

#pragma mark - network request
- (void)requestMineInfo {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineInfo] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"个人中心返回成功：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] updateLoginInfoWithMineInfo:responseObject];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"个人中心失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosLikeAndCommentCnt {
    // 获取未读消息(点赞、评论、回复)的数量
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiNewMessage] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求未读消息返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] mineNewMsgWithDictionary:responseObject];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求未读消息失败：%@", error);
    }];
}

#pragma mark - getters and setters
- (UIView *)msgRedDot {
    if (!_msgRedDot) {
        _msgRedDot = [[UIView alloc] initWithFrame:CGRectMake(34, 12, 5, 5)];
        _msgRedDot.backgroundColor = [UIColor xd_colorWithHex:0xD0011B];
        _msgRedDot.layer.masksToBounds = YES;
        _msgRedDot.layer.cornerRadius = 2.5;
        _msgRedDot.hidden = YES;
    }
    return _msgRedDot;
}
- (NSArray<NSArray *> *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@[@{@"title" : @"个人主页", @"isExpanded" : @"0"}],
                        @[@{@"title" : @"我的店铺", @"isExpanded" : @"1"}],
                        @[@{@"title" : @"我的门票", @"isExpanded" : @"0"},
                          @{@"title" : @"关注的展会", @"isExpanded" : @"0"},
                          @{@"title" : @"展会订单", @"isExpanded" : @"0"}]];
    }
    return _titleArray;
}

//- (KABMineInfo *)mineInfo {
//    return [KABModel sharedInstance].mineInfo;
//}

- (KABLoginModel *)userInfo {
    return [KABModel sharedInstance].userInfo;
}

@end
